<!--
 * @Description: 选择用户
 * @Author: DHL
 * @Date: 2022-04-08 09:04:53
 * @LastEditors: DHL
 * @LastEditTime: 2023-03-08 14:48:08
-->
<template>
  <tw-dialog
    v-model="visible"
    title="选择人员"
    :loading="loading"
    :showZoom="false"
    width="1100px"
    height="660px"
    heightContent="640px"
    customClass="select-user-wrapper"
    @close="handleClose"
  >
    <splitpanes class="default-theme">
      <pane :size="20" style="padding-right: 10px">
        <organizationTree
          ref="orgTreeRef"
          :draggable="false"
          @nodeClick="handleNodeClick"
        ></organizationTree>
      </pane>

      <pane :size="80">
        <splitpanes class="default-theme">
          <pane :size="70" style="padding-right: 7px">
            <tw-layout
              @refresh="handleRefresh"
              @search="handleSearch"
              @reset="handleReset"
              :padding="false"
            >
              <!-- 查询表单 -->
              <template #header>
                <el-form ref="searchFormRef" :model="searchForm" label-width="90px">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="登陆名称">
                        <el-input
                          v-model="searchForm.loginName"
                          clearable
                          placeholder="请输入登陆名称"
                        ></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="姓名">
                        <el-input
                          v-model="searchForm.name"
                          clearable
                          placeholder="请输入姓名"
                        ></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="用户类型">
                        <el-select
                          v-model="searchForm.userType"
                          clearable
                          placeholder="请选择用户类型"
                        >
                          <tw-dic dicKey="USERTYPE"></tw-dic>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="用户状态">
                        <el-select
                          v-model="searchForm.status"
                          clearable
                          placeholder="请选择用户状态"
                        >
                          <tw-dic dicKey="USER_STATUS"></tw-dic>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </template>

              <!-- 数据表格 -->
              <tw-table
                ref="tableRef"
                :loading="loading"
                :options="tableOptions"
                :events="tableEvents"
                :data="tableData"
                @search="searchList"
              >
              </tw-table>
            </tw-layout>
          </pane>
          <pane :size="30" class="selected-user-wrapper">
            <tw-layout :btnsWidth="50" :visibleRefreshBtn="false" :padding="false">
              <!-- 按钮组 -->
              <template #toolbar>
                <div class="custom-toolbar">
                  <div class="user-num">已选择 {{ state.userList.length }} 人</div>
                  <el-button class="item" type="primary" @click="handleSubmit()">
                    <svg-icon iconClass="plus"></svg-icon>
                    确定人员
                  </el-button>
                </div>
              </template>

              <div>
                <div class="user-list">
                  <el-scrollbar height="100%">
                    <draggable
                      :list="state.userList"
                      item-key="id"
                      ghost-class="ghost"
                      chosen-class="chosen"
                      animation="300"
                      @start="handleStart"
                      @end="handleEnd"
                    >
                      <template #item="{ element }">
                        <div class="user-item">
                          <div class="name">{{ element.name }}</div>
                          <div class="icon" @click="handleDelete(element)">
                            <svg-icon iconClass="delete" title="删除"></svg-icon>
                          </div>
                        </div>
                      </template>
                    </draggable>
                  </el-scrollbar>
                </div>
              </div>
            </tw-layout>
          </pane>
        </splitpanes>
      </pane>
    </splitpanes>
  </tw-dialog>
</template>

<script setup lang="ts" name="SelectUser">
  import { reactive, ref } from 'vue'
  import { assign, cloneDeep } from 'lodash-es'
  import { TwTableOptions } from '@/types/table.d'
  import { UserModel, UserPageParams } from '@/api/system/model/userModel'
  import { searchUsersList } from '@/api/system/user'
  import { ElMessage } from 'element-plus'
  import { arrayRemoveByPropertyValue } from '@/utils/arrayUtils'
  import { Splitpanes, Pane } from 'splitpanes'
  import 'splitpanes/dist/splitpanes.css'
  import draggable from 'vuedraggable'
  import organizationTree from './organizationTree.vue'

  const emit = defineEmits(['submit'])

  //////////////////////////////////////////////////
  // 属性
  //////////////////////////////////////////////////

  /**
   * 显示弹框
   */
  const visible = ref(false)

  const loading = ref(false)

  /**
   * 表格数据
   */
  const tableData = ref()

  /**
   * 查询表单
   */
  const searchFormRef = ref()

  /**
   * 数据列表
   */
  const tableRef = ref()

  const state = reactive({
    userList: [] as Array<UserModel> // 选中用户
  })

  //////////////////////////////////////////////////
  // 查询表单
  //////////////////////////////////////////////////

  const defaultSearchForm = {
    orgId: '',
    loginName: '', // 登陆名称
    name: '', // 姓名
    userType: '', // 用户类型
    phone: '', // 手机号码
    mail: '', // 邮箱
    status: '1', // 用户状态（0，失效；1，生效）
    position: '' // 职务
  }

  /**
   * 查询表单
   */
  const searchForm = reactive(cloneDeep(defaultSearchForm))

  //////////////////////////////////////////////////
  // 表格
  //////////////////////////////////////////////////

  /**
   * 表格配置
   */
  const tableOptions = reactive<TwTableOptions>({
    id: 'userListTable',
    checkboxConfig: {
      reserve: false,
      trigger: 'row'
    },
    sortConfig: {
      defaultSort: [{ field: 'loginName', order: 'asc' }]
    },
    columns: [
      // { type: 'checkbox', fixed: 'left', title: '', align: 'center', width: 40 },
      { type: 'seq', fixed: 'left', title: '序号', width: 50 },
      { field: 'loginName', title: '登陆名称', sortable: true, minWidth: 110 },
      { field: 'name', title: '姓名', sortable: true, minWidth: 110 }
      // { field: 'orgName', title: '机构', sortable: false, minWidth: 100 }
      // {
      //   field: 'status',
      //   title: '用户状态',
      //   sortable: true,
      //   width: 100,
      //   params: { dict: 'USER_STATUS' }
      // },
      // {
      //   field: 'userType',
      //   title: '用户类型',
      //   sortable: true,
      //   width: 100,
      //   params: { dict: 'USERTYPE' }
      // }
      // { field: 'position', title: '职务', sortable: true },
      // { field: 'phone', title: '手机号码' },
      // { field: 'mail', title: '邮箱' }
    ]
  })

  /**
   * 绑定事件
   */
  const tableEvents = reactive({
    cellClick: function ({ row }) {
      const exists = state.userList.some((item) => item.id === row.id)
      if (!exists) {
        state.userList.push(row)
      }
    }
  })

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 查询表格数据函数
   * @param queryParams
   */
  function searchList(queryParams: UserPageParams) {
    loading.value = true

    searchUsersList(
      assign(queryParams, searchForm, {
        isAllChildNode: '1',
        orgId: selectOrg.id
      })
    )
      .then((result) => {
        tableData.value = result
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 查询表格数据
   */
  function handleSearch() {
    tableRef.value.handleQuery()
  }

  /**
   * 刷新
   */
  function handleRefresh() {
    tableRef.value.handleReload()
  }

  /**
   * 重置
   */
  function handleReset() {
    assign(searchForm, cloneDeep(defaultSearchForm))
    tableRef.value.handleQuery()
  }

  /**
   * 显示弹框
   */
  function handleOpen(params: any) {
    visible.value = true
    state.userList = []
    if (params) {
      state.userList = cloneDeep(params)
    }
  }

  /**
   * 关闭弹框
   */
  function handleClose() {
    visible.value = false
  }

  /**
   * 提交当前选中行数据
   */
  function handleSubmit() {
    if (state.userList.length < 1) {
      ElMessage.warning('请选择用户')
      return
    }

    emit('submit', state.userList)

    handleClose()
  }

  /**
   * 删除
   * @param row
   */
  function handleDelete(row: UserModel) {
    arrayRemoveByPropertyValue(state.userList, 'id', row.id)
  }

  /**
   * 拖拽开始
   */
  function handleStart() {}

  /**
   * 拖拽结束
   */
  function handleEnd() {}

  //////////////////////////////////////////////////
  // 机构树
  //////////////////////////////////////////////////
  const orgTreeRef = ref()

  /**
   * 选中的组织机构
   */
  let selectOrg: any = {}

  /**
   * 节点点击事件
   */
  function handleNodeClick(treeNode?: Node) {
    selectOrg = treeNode ? treeNode : {}
    handleRefresh()
  }

  defineExpose({ handleOpen })
</script>

<style lang="scss" scoped>
  .select-user-wrapper {
    height: 100%;
    font-size: 14px;

    .splitpanes__pane {
      background-color: #ffffff;
    }

    .selected-user-wrapper {
      .custom-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        .user-num {
          padding: 10px 0px;
        }
      }

      .user-list {
        height: calc(100% - 35px);
        .user-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px;
          border-radius: 3px;
          cursor: pointer;

          &:hover {
            background-color: #ebedf0;
          }

          .icon {
            color: #f56c6c;
            .svg-icon {
              width: 1.1em;
              height: 1.1em;
            }
          }

          &.chosen {
            cursor: move;
          }
        }
      }
    }
  }
</style>
